#!/usr/bin/env python

import os
import sys
import string
import shutil
import re
import time
import platform

osInfo = platform.platform()
if "Darwin" in osInfo:
	protoc = "protoc/mac/protoc340"
elif "Windows" in osInfo:
	protoc = "protoc/win32/protoc340.exe"
pbPath = "../hope-serverpro/src/pb/"
base = os.getcwd()
if os.path.exists("pb_go"):
	shutil.rmtree("pb_go")
os.mkdir("pb_go")
cur_list = os.listdir(base)
for item in cur_list:
	full_path = os.path.join(base, item)
	if os.path.isfile(full_path):
	    if full_path.endswith(".proto"):
			print full_path
			os.system('%s/%s --go_out=pb_go -I=%s %s'% (base,protoc,base,full_path))

pb_list = os.listdir("pb_go")
pattern = re.compile(r'import ([a-z0-9\_]*) "\."')
for item in pb_list:
	full_path = os.path.join(base+"/pb_go/", item)
	pbFile = file(full_path,'r')
	pbFileNew  = file(full_path+'.tmp','w')
	for line in pbFile.readlines():
		pbFileNew.writelines(pattern.sub(r'import \1 "pb/\1"',line))
	pbFile.close()
	pbFileNew.close()
	os.remove(full_path)
	os.rename(full_path+'.tmp',full_path)
			
if os.path.exists(pbPath):
	shutil.rmtree(pbPath)
pb_list = os.listdir("pb_go")
for item in pb_list:
	full_path = os.path.join(base+"/pb_go/", item)
	if full_path.endswith(".pb.go"):
		package = item.replace(".pb.go","")
		# print package
		if not os.path.exists(pbPath+package):
			#print pbPath+package
			os.makedirs(pbPath+package)
		toPath = pbPath+package+"/"+item
		shutil.copy(full_path,toPath)
		#print "copy "+full_path+" to "+toPath

shutil.rmtree("pb_go")
time.sleep(6)